<?php
namespace app\home\model;

use think\Model;

class Account extends Model {
    //送积分
    function getOne($where) {
        if (!$where['user_id']) {
            return null;
        }
        $user_id = $where['user_id'];
        $result = $this->where($where)->find();
        if (!$result) {
            $id = $this->insert([
                    'user_id' => $user_id,
                    'total' => 0
            ]);
            $result = [
                    'id' => $id,
                    'user_id' => $user_id,
                    'total' => 0,
                    'balance_jf' => 0,
                    'balance_frost' => 0,
            ];
        }

        $time_from = strtotime(date('Y-m-d 00:00:00'));
        $time_to = strtotime(date('Y-m-d 23:59:59'));
        $money = db('account_recharge')->where(['status' => 1, 'verify_time' => ['between', [$time_from, $time_to]], 'user_id' => $user_id])->sum('money');

        $result['balance_frost_today'] = $money?:0;//今日充值金额
        $result['balance_frost_can'] = $result['balance_frost'] - $result['balance_frost_today'];
        $result['free_num'] = model('account', 'logic')->getFreeNum(['user_id' => $user_id]);

        return $result;
    }

    //更新积分
    function updateBalanceJf($data = []) {
        return $this->where(['user_id' => $data['user_id']])->setInc('balance_jf', $data['score']);
    }

    //更新
    function edit($where = [], $data = []) {
        return $this->where($where)->update($data);
    }

    static function GetList($data = array()) {
        global $mysql;
        $_sql = "where 1=1 ";
        echo 1;
        //搜索用户id
        if (isset($data['user_id'])) {
            $_sql .= " and p1.user_id = '{$data['user_id']}'";
        }

        //搜索用户名
        if (isset($data['username'])) {
            $_sql .= " and p2.username like '%" . urldecode($data['username']) . "%'";
        }
        if (!isset($data['limit']))
            $_select = "p1.*,p5.realname,p2.username,czje(p1.user_id) as czje,txje(p1.user_id) as txje ";
        else
            $_select = "p1.*,p5.realname,p2.username,p4.adminname,czje(p1.user_id) as czje,txje(p1.user_id) as txje,tjjl(p1.user_id) as tjjl,yslx(p1.user_id) as yslx,getTJR(p1.user_id) as tjr";

        $_order = " order by p1.id desc";
        $sql = "select SELECT from {account} as p1 
				 left join {users} as p2 on p1.user_id=p2.user_id
                 left join {users_vip} as p3 on p3.user_id=p1.user_id
                 left join {users_admin} as p4 on p4.user_id=p3.kefu_userid
                 left join {approve_realname} as p5 on p5.user_id=p1.user_id
				SQL ORDER LIMIT";

        //导出数据
        if (isset($data['excel']) == "true") {

        } //是否显示全部的信息
        elseif (isset($data['limit'])) {
            if ($data['limit'] != "all") {
                $_limit = "  limit " . $data['limit'];
            }
            $list = $mysql->db_fetch_arrays(str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($_select, $_sql, $_order, $_limit), $sql));
            //重新统计待还金额
            for ($i = 0; $i < count($list); $i++) {
                $new_sql = "select repay_status,sum(repay_account) as anum from  `{borrow_repay}` where user_id='{$list[$i]['user_id']}' and status=1 group by repay_status";
                $new_result = $mysql->db_fetch_arrays($new_sql);
                $anum = 0.00;
                foreach ($new_result as $key => $value) {
                    if ($value['repay_status'] == 0) {
                        $anum = $value['anum'];
                    }
                }
                $list[$i]['repay'] = $anum;
            }
            return $list;
        }

        //判断总的条数
        $row = $mysql->db_fetch_array(str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array('count(1) as num', $_sql, '', ''), $sql));
        $total = intval($row['num']);
        //分页返回结果
        $data['page'] = !isset($data['page']) ? 1 : $data['page'];
        $data['epage'] = !isset($data['epage']) ? 10 : $data['epage'];
        $total_page = ceil($total / $data['epage']);
        $_limit = " limit " . ($data['epage'] * ($data['page'] - 1)) . ", {$data['epage']}";
        $list = $mysql->db_fetch_arrays(str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($_select, $_sql, $_order, $_limit), $sql));

        //$sql = "select * from ";
        //总可用余额 总冻结金额
        $_total = $mysql->db_fetch_arrays(str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($_select, $_sql, $_order, ""), $sql));
        $total_balance = 0;
        $total_frost = 0;
        foreach ($_total as $key => $value) {
            $total_balance += $value['balance'];
            $total_frost += $value['frost'];
        }

        //重新统计待还金额
        for ($i = 0; $i < count($list); $i++) {
            $new_sql = "select repay_status,sum(repay_account) as anum from  `{borrow_repay}` where user_id='{$list[$i]['user_id']}' and status=1 group by repay_status";
            $new_result = $mysql->db_fetch_arrays($new_sql);
            $anum = 0.00;
            foreach ($new_result as $key => $value) {
                if ($value['repay_status'] == 0) {
                    $anum = $value['anum'];
                }
            }
            $list[$i]['repay'] = $anum;
        }
        //返回最终的结果
        $result = array('list' => $list ? $list : array(), 'total' => $total, 'page' => $data['page'], 'epage' => $data['epage'], 'total_page' => $total_page, 'total_balance' => $total_balance, 'total_frost' => $total_frost);
        return $result;
    }


    /**
     * 资金记录列表
     *
     * @return Array
     */
    function GetLogList($data = []) {

        $_sql = "where 1=1 ";

        //搜索用户id
        if (isset($data['user_id'])) {
            $_sql .= " and p1.user_id = '{$data['user_id']}'";
        }

        //搜索用户名
        if (isset($data['username'])) {
            $_sql .= " and p2.username = '" . urldecode($data['username']) . "'";
        }

        if (isset($data['type']) && $data['type'] != '') {
            $type_array = [];
            switch ($data['type']) {
                case 1: //充值
                    $type_array = ["recharge", "recharge_fee", "online_recharge", "recharge_fee", "addjl"];
                    break;
                case 2: //提现
                    $type_array = ["cash_frost", "cash_fee", "cash", "cash_success", "cash_false", "cash_cancel"];
                    break;
                case 3: //投资
                    $type_array = [
                            "tender_success", "borrow_success", "tender_success_frost", "tender_recover_yes", "tender", "tender_late_repay_yes",
                            "tender_false", "tender_user_cancel", "tender_recover_fee_service", "tender_late_repay_yes", "tender_recover_advance_fee_advance",
                            "tender_recover_advance_fee_advance", "tender_recover_advance_frost_yes", "borrow_repay_advance_fee_advance", "tender_award_add",
                            "tender_recover_late", "tender_over", "touzishouyi", "tender_interest_award_add"
                    ];
                    break;
                case 4: //其他
                    $type_array = [
                            "recharge", "recharge_fee", "online_recharge", "recharge_fee", "addjl",
                            "cash_frost", "cash_fee", "cash", "cash_success", "cash_false", "cash_cancel",
                            "tender_success", "borrow_success", "tender_success_frost", "tender_recover_yes", "tender", "tender_late_repay_yes",
                            "tender_false", "tender_user_cancel", "tender_recover_fee_service", "tender_late_repay_yes", "tender_recover_advance_fee_advance",
                            "tender_recover_advance_fee_advance", "tender_recover_advance_frost_yes", "borrow_repay_advance_fee_advance", "tender_award_add",
                            "tender_recover_late", "tender_over", "touzishouyi", "tender_interest_award_add"];
                    break;
            }
            if ($type_array) {
                if ($data['type'] == 4) {
                    $_sql .= " and p1.type not in ('" . join("','", $type_array) . "')";
                } else {
                    $_sql .= " and p1.type in ('" . join("','", $type_array) . "')";
                }
            } else {
                $_sql .= " and p1.type = '{$data['type']}'";
            }
        }

        if (isset($data['time'])) {
            switch ($data['time']) {
                case 1:
                case 3:
                case 6:
                    $_sql .= " and p1.addtime <= " . strtotime('+ ' . $data['time'] . '  months') . " and p1.addtime >= " . strtotime('-' . $data['time'] . ' months ');
                    break;
                case 7:
                    $_sql .= " and p1.addtime <= " . strtotime('+ ' . $data['time'] . '  days') . " and p1.addtime >= " . strtotime('-' . $data['time'] . ' days');
                    break;
            }
        }
        $prefix = config('database.prefix');
        $_select = "p1.*,p2.username";
        $_order = " order by p1.id desc ";
        $sql = "select SELECT from {$prefix}account_log as p1 
				 left join {$prefix}users as p2 on p1.user_id=p2.user_id
				SQL ORDER LIMIT";

        if (isset($data['limit'])) {
            if ($data['limit'] != "all") {
                $_limit = "  limit " . $data['limit'];
            }
            return db()->query(str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($_select, $_sql, $_order, $_limit), $sql));
        }

        //分页返回结果
        $data['page'] = !isset($data['page']) ? 1 : $data['page'];
        $data['epage'] = !isset($data['epage']) ? 10 : $data['epage'];
        $_limit = " limit " . ($data['epage'] * ($data['page'] - 1)) . ", {$data['epage']}";
        $list = db()->query(str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($_select, $_sql, $_order, $_limit), $sql));

        return $list;
    }
}